import React, { useState, useRef, useEffect } from 'react';
import { Button, Input, Tag, message, Spin, Badge } from 'antd';
import debounce  from 'lodash.debounce';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { history } from 'umi';
import ParentOrgListComponent from '../System/components/ParentOrgListComponent';
import TagCommonComponent from '../System/components/TagCommonComponent';
import GroupListComponent from '../System/components/GroupListComponent';
import { PlanItemParam, TableListItem } from './data.d';
import styles from './index.less';
import { planAdd, planUpdate } from './service';
import { deviceList} from '../Equipment/service';

const { Search } = Input;
let planInfo = new Object as PlanItemParam;
const EquipmentList: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [spinning, setSpinning] = useState<boolean>(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState<TableListItem[]>([]);
  const [disabled, handleDisabled] = useState<boolean>(true);//所属分组是否可用，根据上级机构

  useEffect(() => {
    planInfo = props.location.state;
    if(planInfo && planInfo.deviceIds){
      setSelectedRowKeys(planInfo.deviceIds);
    }else{
      setSelectedRowKeys([]);
    }
  },[]);

  //重置监听
  const onReset = () =>{
  handleDisabled(true);
  }

  //添加计划
  const planAddCommand = () => {
    new Promise((resolve, reject) => {
      planAdd(planInfo)
        .then((res) => {
          setSpinning(false);
          if(res){
            if (res.code === 200) {
              message.success('添加成功',1);
              history.push('/plan/list/');
              resolve(true);
            }else{
              message.error(res.message+' 添加失败请重试！');
              resolve(false)
            };
          }else{
            message.error('请求失败！');
          }
          
        })
        .catch((error) => {
          setSpinning(false);
          reject(error);
        });
    });
  }

  //编辑计划
  const planUpdateCommand = () => {
    new Promise((resolve, reject) => {
      planUpdate(planInfo.id,planInfo)
        .then((res) => {
          setSpinning(false);
          if(res){
            if (res.code === 200) {
              message.success('保存成功',1);
              history.push('/plan/list/');
              resolve(true);
            }else{
              message.error(res.message+' 编辑失败请重试！');
              resolve(false);
            };
          }else{
            message.error('请求失败！');
            resolve(false);
          }
        })
        .catch((error) => {
          setSpinning(false);
          reject(error);
        });
    });
  }
  const finish = () => {
    if(selectedRowKeys == undefined || selectedRowKeys.length == 0){
      message.warn('请选择设备');
      return;
    }
    planInfo.deviceIds = selectedRowKeys.toString();
    //播放模式：持续播放
    if(planInfo.playMode == 0){
      console.log("=================")
      planInfo.startDatetime = null;
      planInfo.endDatetime = null;
    }
    //发布方式: 实时发布
    if(planInfo.publishWay == 0){
      delete planInfo.publishDatetimeType; //发布时间
      delete planInfo.publishDatetime; //选择时间
    }else{//定时发布
      if(planInfo.publishDatetimeType == "default"){ //发布时间 默认时间
        delete planInfo.publishDatetime; //选择时间
      }
    }
    setSpinning(true);
    if(planInfo.id){
      //编辑计划
      planUpdateCommand();
    }else{
      //添加计划
      planAddCommand();
    }
    return;
    
  }
  const onSelectChange = ( selectedRowKeys, selectedRows) =>{
    setSelectedRowKeys(selectedRowKeys);
    setSelectedRows(selectedRows);
  }

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '设备名称',
      dataIndex: 'name',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入设备名称"
              onSearch={debounce(value=>{form.submit()}, 500)}
              onChange={debounce(value=>{form.submit()}, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: 'MAC地址',
      dataIndex: 'mac',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '所属分组',
      dataIndex: 'groups',
      valueType: 'text',
      hideInSearch: true, 
      width:200,
      render: groups => (
        <>
          {groups?.map((group, index) => {
            return (
              <Tag color="blue" key={index} title={group} style={{marginBottom:5,display:'inline-block',overflow:'hidden',whiteSpace:'pre',textOverflow:'ellipsis',maxWidth:180}}>
                {group}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '分辨率',
      dataIndex: 'resolution',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '所属机构',
      dataIndex: 'orgId',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <ParentOrgListComponent 
              defaultvalue={-1}
              type="orgId"
              selectChange={(value) => {
                form.setFieldsValue({
                  "orgId": value,
                  "groupId":null,
                  "tagIds":null,
                });
                if(value){
                  handleDisabled(false);
                }else{
                  handleDisabled(true);
                }
                form.submit();
              }}
              >
            </ParentOrgListComponent>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '所属机构',
      dataIndex: 'orgName',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '所属分组',
      dataIndex: 'groupId',
      hideInTable:true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        const orgId = form.getFieldValue('orgId');
        let value = "";
        if (status !== 'open') {
          return (
            <GroupListComponent 
              defaultvalue={-1}
              value={value}
              disabled={disabled}
              orgId={orgId?orgId:-1}
              selectChange={(value) => {
                form.setFieldsValue({"groupId": value? value:null});
                form.submit();
              }}
            >
          </GroupListComponent>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '当前计划',
      dataIndex: 'nowPlanName',
      valueType: 'text',
      hideInSearch: true,
      width:150,
      render:  (_, record) => (
        record.nowPlanName? record.nowPlanName: (
          record.defaultPlanName?<Badge count="默认计划" style={{background:'#1890ff', color:'#fff'}} offset={[30, 0]}><label>{record.defaultPlanName}</label></Badge>:"--")
      )
    },
    {
      title: '在线状态',
      dataIndex: 'onlineStatus',
      valueType: 'text',
      hideInSearch: true,
      valueEnum: {
        ONLINE: { text: '在线', status: 'Success' },
        OFFLINE: { text: '离线', status: 'Warning' },
      },
    },
    {
      title: '标签',
      dataIndex: 'tagIds',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        const orgId = form.getFieldValue('orgId');
        let value = "";
        if (status !== 'open') {
          return (
            <TagCommonComponent
              value={value}
              topOrgId = {orgId>0?orgId:JSON.parse(localStorage.getItem("user")).topOrgId}  
              selectChange={(values) =>{
                  form.setFieldsValue({"tagIds": values.toString()});
                  form.submit();
                }
              }
            >
           </TagCommonComponent>
          );
        }
        return defaultRender(_);
      },
      hideInTable:true,
      valueType: 'text',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'text',
      width:150,
      hideInSearch: true, 
      render: tags => (
        <>
          {tags?.map((tag, index) => {
            return (
              <Tag color="blue" key={index} title={tag.name} style={{marginBottom:5,display:'inline-block',overflow:'hidden',whiteSpace:'pre',textOverflow:'ellipsis',maxWidth:130}}>
                {tag.name}
              </Tag>
            );
          })}
        </>
      ),
    },
  ];

  return (
    <Spin spinning={spinning} tip="如果该计划引用的节目过大可能需要几分钟，请耐心等待..." size="large" style={{marginTop: '20vh',fontSize:16}}>
      <PageContainer title={planInfo?.id?"编辑计划":"新建计划"}>
        <ProTable<TableListItem>
          headerTitle="选择设备"
          options={false}
          actionRef={actionRef}
          rowKey="key"
          search={{
            labelWidth: 120,
          }}
          onReset={onReset}
          pagination={{ showQuickJumper: true,defaultPageSize: 10 }}
          request={(params, sorter, filter) => deviceList({ ...params, sorter, filter })}
          columns={columns}
          // rowSelection={rowSelection}
          onLoad={()=>{
            setSelectedRowKeys(selectedRowKeys);
            setSelectedRows(selectedRows);
          }}
          rowSelection={{
            selectedRowKeys:selectedRowKeys,
            onSelect:(record, selected)=>{
              if(selected){//选中
                setSelectedRowKeys([...selectedRowKeys,record.key]);
                setSelectedRows([...selectedRows,record]);
              }else{//取消选中
                const newKeys = selectedRowKeys.concat();
                const index = newKeys.indexOf(record.key);
                newKeys.splice(index, 1);
                setSelectedRowKeys(newKeys);
                
                const newRows = selectedRows.concat();
                for(let i=0;i<selectedRows.length;i++){
                  if(i == index){
                    newRows.splice(index, 1);
                  }
                }
                setSelectedRows(newRows);
              }
            },
            onSelectAll:(selected, selectedRows1, changeRows)=>{
              if(selected){//全选
                const keys = [];
                for(let i=0;i<changeRows.length;i++){
                  const record = changeRows[i];
                  keys.push(record.key);
                }
                setSelectedRowKeys([...selectedRowKeys,...keys]);
                setSelectedRows([...selectedRows,...changeRows]);
              }else{//取消全选
                const newSelectedRowKeys = selectedRowKeys.concat();
                const newSelectedRows = selectedRows.concat();
                for(let i=0;i<changeRows.length;i++){
                  const record = changeRows[i];
                  for(let j=0;j<newSelectedRowKeys.length;j++){
                    if(record.key == newSelectedRowKeys[j]){
                      newSelectedRowKeys.splice(j, 1);
                      newSelectedRows.splice(j, 1);
                    }
                  }
                }
                setSelectedRowKeys(newSelectedRowKeys);
                setSelectedRows(newSelectedRows);
              }
            }
          }}
          tableAlertOptionRender={() => {
            return (<a onClick={() => {
              setSelectedRowKeys([]);
              setSelectedRows([]);
              actionRef.current?.clearSelected?.();
            }}>清空</a>)
          }}
        />
        <footer className={styles.footer}>
          <Button style={{marginRight:50}} onClick={() => history.push('/plan/list/')}>取消</Button>
          <Button style={{marginRight:50}} onClick={() => {
            if(planInfo.deviceIds && !Array.isArray(planInfo.deviceIds)){
              planInfo.deviceIds = planInfo.deviceIds.split(',').map(Number);
            }
            history.push({pathname:'/plan/list/new',state:planInfo})}
          }>上一步</Button>
          <Button type="primary" onClick={() => finish()}>完成</Button>
        </footer>
      </PageContainer>
    </Spin>
  );
};

export default EquipmentList;
